package com.jxbeidou.gateway.handler;

import com.jxbeidou.gateway.util.ReactiveHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: jxbeidou-basic
 * @ClassName: GatewayWebExceptionHandler
 * @description: 微服务网关全局异常
 * @author: 杜晓祥
 * @create: 2023-12-22 16:24
 * 版权所有：交信北斗(北京)信息科技有些公司
 */
@Configuration
@Slf4j
public class GatewayWebExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }
        String msg;
        if (ex instanceof NotFoundException) {
            msg = "服务未找到";
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        } else {
            msg = "内部服务器错误";
        }
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());
        log.debug("[网关异常处理]", ex);

        return ReactiveHttpUtil.responseResult(response, msg);
    }
}
